﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Globalization;
using System.Threading;
using System.Transactions;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Practices.Prism.Events;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;


namespace P2.Cuberry
{
   
    public partial class Shell : Window, IShellView
    {
        public event EventHandler<DataEventArgs<int>> LanguageChanged = delegate { };

        public Shell()
        {
            CuberrySplash.Loading("Initializing Shell....");
            Thread.Sleep(1500);

            InitializeComponent();            

            try
            {
                foreach (var lang in P2.Cuberry.Framework.Helper.P2Language.GetLanguages())
                {
                    languages.Items.Add(lang.LanguageID);
                }

                languages.SelectedItem = Thread.CurrentThread.CurrentCulture;

                P2.Cuberry.Framework.Helper.P2Validator.YellowErrorDialog = new P2.Cuberry.Framework.Helper.P2YellowPresenter(); //this.Container.Resolve<P2.Cuberry.Framework.Helper.IP2YellowErrorDialog>();

                this.languages.SelectionChanged += new SelectionChangedEventHandler(languages_SelectionChanged);
                this.Closing += new System.ComponentModel.CancelEventHandler(Shell_Closing);
                
                CuberrySplash.Loading("Success....");
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }      
        }

             
        public void ShowView()
        {
            this.Show();
            this.LoadUserSettings();            
        }

                
        void languages_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                P2Translator.Culture = CultureInfo.GetCultureInfo(languages.SelectedItem.ToString());
                this.FlowDirection = FlowDirection.LeftToRight;
                if (P2Translator.Culture.TextInfo.IsRightToLeft)
                    this.FlowDirection = FlowDirection.RightToLeft;
                LanguageChanged(this, new DataEventArgs<int>(0));
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        void Shell_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                this.SaveUserSettings();
                if (P2.Cuberry.Framework.Helper.P2Validator.YellowErrorDialog != null)
                {
                    P2.Cuberry.Framework.Helper.P2Validator.YellowErrorDialog.CloseWindow();
                    P2.Cuberry.Framework.Helper.P2Validator.YellowErrorDialog = null;
                }
                
            }
            catch (Exception ex)
            {
                //P2UIExceptionHandler.handleException(ex, this.Name, "MainDeskConstructor.07", true, true, "");
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        //Load settings when starting in the MainForm_Load event
        private void LoadUserSettings()
        {
            try
            {                
                base.Width = Properties.Settings.Default.Width;
                base.Height = Properties.Settings.Default.Height;
                P2Translator.Culture = Properties.Settings.Default.ApplicationLanguage;
                System.Text.StringBuilder sb = new System.Text.StringBuilder(P2Translator.Culture.TwoLetterISOLanguageName);
                sb = sb.Replace(sb[0], Char.ToUpper(sb[0]), 0, 1);
                this.languages.SelectedItem = sb.ToString();

                this.FlowDirection = FlowDirection.LeftToRight;
                if(P2Translator.Culture.TextInfo.IsRightToLeft)                
                    this.FlowDirection = FlowDirection.RightToLeft;

                this.lblUserName.Content = P2.Cuberry.Framework.Security.User.Current.UserID;
                this.lblUserGroup.Content = P2.Cuberry.Framework.Security.User.Current.UserGroupName;

                if (this.lblUserGroup.Content.Equals(P2Translator.GetResource("NewUser")))
                {
                    this.btnRegister.Visibility = System.Windows.Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                //P2UIExceptionHandler.handleException(ex, this.Name, "MainDeskConstructor.05", true, true, "");
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        //Save settings while closing: In the MainForm_Closing event        
        private void SaveUserSettings()
        {
            try
            {                                
                    Properties.Settings.Default.Height = base.Height;
                    Properties.Settings.Default.Width = base.Width;
                    Properties.Settings.Default.ApplicationLanguage = (CultureInfo)P2Translator.Culture;
                
                Properties.Settings.Default.Save();
            }
            catch (Exception ex) //AM:TC
            {
                //P2UIExceptionHandler.handleException(ex, this.Name, "MainDeskConstructor.04", true, true, "");
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }
        

        public void AddMainMenuItem(int ID, string Title)
        {
            this.MainMenuInst.AddButton(ID, Title);
        }


        public void Reset()
        {
            this.MainMenuInst.Reset();
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (MessageBox.Show(P2Translator.GetResource("RegisterWarning") + " (" + P2.Cuberry.Framework.Security.User.Current.UserID + ")?", P2Translator.GetResource("Warning"), MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Security", Properties.Settings.Default.EntityResources);
               
                
                using (DAL.NewUserDataContext db = new DAL.NewUserDataContext(connectionString))
                {
                    using (TransactionScope ts = new TransactionScope())
                    {
                        DAL.XSecUser newUser = DAL.XSecUser.CreateXSecUser(P2.Cuberry.Framework.Security.User.Current.UserID, true);

                        newUser.UserGroupID = 0;
                        newUser.CreatedBy = P2.Cuberry.Framework.Security.User.Current.UserID;
                        newUser.EditedBy = P2.Cuberry.Framework.Security.User.Current.UserID;
                        newUser.CreatedOn = DateTime.Now;
                        newUser.EditedOn = DateTime.Now;
                        
                        db.AddToXSecUser(newUser);

                        db.SaveChanges();
                        ts.Complete();

                    }
                }

                MessageBox.Show(P2Translator.GetResource("RestartApp2"), "", MessageBoxButton.OK);

                System.Diagnostics.Process.Start(Application.ResourceAssembly.Location);
                Application.Current.Shutdown();
                

            }
            catch (Exception ex)
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

    }
}
